'use client'

import { useState } from "react"
import { EditCategoryDialog } from "./edit-category-dialog"
import { PencilIcon, TrashIcon } from "@heroicons/react/24/outline"
import { deleteCategory } from "@/actions/category"

type SerializedCategory = {
  id: number
  name: string
  createdAt: string
  updatedAt: string
  _count: {
    products: number
  }
}

interface CategoryItemProps {
  category: SerializedCategory
}

export function CategoryItem({ category }: CategoryItemProps) {
  const [isEditOpen, setIsEditOpen] = useState(false)

  const handleDelete = async () => {
    if (category._count.products > 0) {
      alert('该分类下还有商品，不能删除')
      return
    }
    
    if (confirm('确定要删除该分类吗？')) {
      try {
        await deleteCategory(category.id)
      } catch (error) {
        console.error('删除分类失败:', error)
      }
    }
  }

  return (
    <>
      <tr className="group">
        <td className="px-6 py-4 whitespace-nowrap">
          <div className="text-sm font-medium text-gray-900">{category.name}</div>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <div className="text-sm text-gray-900">{category._count.products}</div>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <div className="text-sm text-gray-900">
            {new Date(category.createdAt).toLocaleString()}
          </div>
        </td>
        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
          <button
            onClick={() => setIsEditOpen(true)}
            className="text-indigo-600 hover:text-indigo-900 mr-4"
          >
            <PencilIcon className="h-5 w-5" />
          </button>
          <button
            onClick={handleDelete}
            className={`text-red-600 hover:text-red-900 ${
              category._count.products > 0 ? 'opacity-50 cursor-not-allowed' : ''
            }`}
            disabled={category._count.products > 0}
          >
            <TrashIcon className="h-5 w-5" />
          </button>
        </td>
      </tr>
      {isEditOpen && (
        <EditCategoryDialog
          category={category}
          open={isEditOpen}
          onClose={() => setIsEditOpen(false)}
        />
      )}
    </>
  )
} 